{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 迭代器\n",
    "* 迭代是Python最强大的功能之一，是访问集合元素的一种方式。\n",
    "* 迭代器是一个可以记住遍历的位置的对象。\n",
    "* 迭代器对象从集合的第一个元素开始访问，直到所有的元素被访问完结束。迭代器只能往前不会后退。\n",
    "* 迭代器有两个基本的方法：iter() 和 next()。\n",
    "* 字符串，列表或元组对象都可用于创建迭代器："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n"
     ]
    }
   ],
   "source": [
    "ls=[1,2,3,5,8]\n",
    "it=iter(ls)\n",
    "print(next(it))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    }
   ],
   "source": [
    "print(next(it))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 迭代器对象可以使用常规for语句进行遍历："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1,2,3,5,8,"
     ]
    }
   ],
   "source": [
    "ls=[1,2,3,5,8]\n",
    "it=iter(ls)\n",
    "for x in it:\n",
    "    print(x,end=',')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 生成器\n",
    "在 Python 中，使用了 yield 的函数被称为生成器（generator）。\n",
    "跟普通函数不同的是，生成器是一个返回迭代器的函数，只能用于迭代操作，更简单点理解生成器就是一个迭代器。\n",
    "在调用生成器运行的过程中，每次遇到 yield 时函数会暂停并保存当前所有的运行信息，返回 yield 的值, 并在下一次执行 next() 方法时从当前位置继续运行。\n",
    "调用一个生成器函数，返回的是一个迭代器对象。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1,1,2,3,5,8,13,21,34,55,89,"
     ]
    }
   ],
   "source": [
    "# 斐波纳契数列\n",
    "def tt(n):\n",
    "    a,b=0,1\n",
    "    while b<n:\n",
    "        yield b\n",
    "        a,b=b,a+b\n",
    "for i in tt(100):\n",
    "    print(i,end=',')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "it=iter(tt(100))\n",
    "for i in it:\n",
    "    print(i,end='')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
